<?php
/**
 * Created by PhpStorm.
 * User: xsp
 * Date: 2018/4/20
 * Time: 15:57
 */

namespace backend\controllers;

use backend\models\Profile;
use common\models\User;
use yii\data\Pagination;
use yii\db\Exception;
use yii\web\Controller;
use Yii;

class UserController extends CommonController
{
    public $layout = 'main';
    protected $mustLogin = ['list','del','add'];
    public function actionList()
    {
        $model = User::find()->joinWith('profile');
        $count = $model->count();
        $page = new Pagination(['totalCount' => $count, 'pageSize' => 3]);
        $data = $model->offset($page->offset)->limit($page->limit)->all();
        return $this->render('list', ['data' => $data, 'page' => $page]);
    }

    public function actionDel()
    {
        $tran = Yii::$app->db->beginTransaction();
        try {
                  $userid = (int)Yii::$app->request->get('userid');
            if (empty($userid)) {
                throw  new Exception("userid为空");
            }

            if (Profile::find()->where(['userid' => $userid])) {
                $res = Profile::deleteAll(['userid' => $userid]);
                if (empty($res)) {
                    throw new Exception("无法删除用户{$userid}");
                }
            }
            if (!User::deleteAll(['userid' => $userid])) {
                throw new Exception("无法删除用户{$userid}");
            }
        $tran->commit();
        } catch (\Exception $e) {
            if(\Yii::$app->db->getTransaction())
            {
                $tran->rollBack();
            }
        }
        $this->redirect(['user/list']);
    }
    public function actionAdd()
    {
        $model = new User();
        if(Yii::$app->request->isPost)
        {
            $data = Yii::$app->request->post();

            if($model->AddUser($data))
            {
                Yii::$app->session->setFlash('info','添加成功');
            }else{
                Yii::$app->session->setFlash('info','添加失败');
            }
        }
        return $this->render('add',['model'=>$model]);
    }
}